'''
Created on 2013. 5. 13.

@author: Lee
'''

from google.appengine.api import channel
from google.appengine.ext import ndb
from kr.community.configure import JINJA_ENVIRONMENT
from kr.community.gaesessions import get_current_session
from kr.community.models import ChatList, ChannelSession, Notice
import webapp2

class MainPage(webapp2.RequestHandler):
    '''
        This is Main Page.
        Summary of site contents.
    '''

    def get(self):
        session = get_current_session()
        template_values = {}
        template = JINJA_ENVIRONMENT.get_template('main.html')
        
        if session.is_active():
            user_key = ndb.Key(urlsafe=session['user'])
            user = user_key.get()
            template_values['user'] = user
            
            chat_token = channel.create_channel(session['user'])
            template_values['chat_token'] = chat_token
            template_values['chat_list'] = ChatList.query().order(-ChatList.timestamp).fetch(200)
            template_values['chat_list'].reverse()
            
            for chat_entry in template_values['chat_list']:
                start_idx = -1
                end_idx = -1
                http_flag = True
                try:
                    start_idx = chat_entry.msg.index("http")
                except ValueError:
                    try:
                        start_idx = chat_entry.msg.index("www")
                        http_flag = False   
                    except ValueError:
                        continue
                try:
                    end_idx = chat_entry.msg.index(" ", start_idx)
                except ValueError:
                    end_idx = len(chat_entry.msg)
                link = chat_entry.msg[start_idx:end_idx]
                if http_flag:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='%s' target='_blank'>%s</a>"%(link, link))
                else:
                    chat_entry.msg = chat_entry.msg.replace(link, "<a href='http://%s' target='_blank'>%s</a>"%(link, link))
            template_values['user_list'] = ChannelSession.query()
            template_values['notice'] = Notice.query().order(-Notice.timestamp).fetch(1)[0]
            template_values['notice'].content = template_values['notice'].content.replace("\n", "<br/>")
            
            self.response.write(template.render(template_values))
        else:
            self.redirect("/login/")